// 设置搜索服务
// 提供设置项的搜索和过滤功能

import { BaseSetting, SettingSearchResult, SettingsCategory, SettingType } from '../types/settings';

// 设置定义数据库（实际项目中可能从配置文件或API获取）
export const SETTINGS_DEFINITIONS: BaseSetting[] = [
  // 编辑器设置
  {
    id: 'editor.fontSize',
    name: '字体大小',
    description: '编辑器中代码的字体大小（像素）',
    category: SettingsCategory.Editor,
    type: SettingType.Number,
    defaultValue: 14,
    currentValue: 14,
    tags: ['字体', '大小', '编辑器', 'font', 'size'],
    group: 'basic'
  },
  {
    id: 'editor.fontFamily',
    name: '字体系列',
    description: '编辑器使用的字体系列',
    category: SettingsCategory.Editor,
    type: SettingType.Font,
    defaultValue: 'Consolas, "Courier New", monospace',
    currentValue: 'Consolas, "Courier New", monospace',
    tags: ['字体', '系列', '编辑器', 'font', 'family'],
    group: 'basic'
  },
  {
    id: 'editor.tabSize',
    name: '制表符大小',
    description: '制表符对应的空格数量',
    category: SettingsCategory.Editor,
    type: SettingType.Number,
    defaultValue: 2,
    currentValue: 2,
    tags: ['制表符', '缩进', '空格', 'tab', 'indent'],
    group: 'basic'
  },
  {
    id: 'editor.wordWrap',
    name: '自动换行',
    description: '当行内容超出编辑器宽度时自动换行',
    category: SettingsCategory.Editor,
    type: SettingType.Boolean,
    defaultValue: false,
    currentValue: false,
    tags: ['换行', '自动', '编辑器', 'wrap', 'line'],
    group: 'basic'
  },
  {
    id: 'editor.autoSave',
    name: '自动保存',
    description: '编辑后自动保存文件',
    category: SettingsCategory.Editor,
    type: SettingType.Boolean,
    defaultValue: true,
    currentValue: true,
    tags: ['自动保存', '保存', '编辑器', 'auto', 'save'],
    group: 'editing'
  },

  // 外观设置
  {
    id: 'appearance.theme',
    name: '颜色主题',
    description: '应用程序的整体颜色主题',
    category: SettingsCategory.Appearance,
    type: SettingType.Select,
    defaultValue: 'auto',
    currentValue: 'auto',
    tags: ['主题', '颜色', '外观', 'theme', 'color'],
    group: 'theme',
    validation: {
      options: [
        { value: 'light', label: '浅色主题' },
        { value: 'dark', label: '深色主题' },
        { value: 'auto', label: '跟随系统' }
      ]
    }
  },
  {
    id: 'appearance.accentColor',
    name: '强调色',
    description: '界面中的强调色，用于按钮、链接等元素',
    category: SettingsCategory.Appearance,
    type: SettingType.Color,
    defaultValue: '#007ACC',
    currentValue: '#007ACC',
    tags: ['颜色', '强调', '按钮', 'accent', 'color'],
    group: 'theme'
  },

  // 快捷键设置
  {
    id: 'keyboard.shortcuts.save',
    name: '保存文件',
    description: '保存当前编辑的文件',
    category: SettingsCategory.Keyboard,
    type: SettingType.Shortcut,
    defaultValue: 'Ctrl+S',
    currentValue: 'Ctrl+S',
    tags: ['快捷键', '保存', '文件', 'shortcut', 'save'],
    group: 'file'
  },
  {
    id: 'keyboard.shortcuts.copy',
    name: '复制',
    description: '复制选中的内容',
    category: SettingsCategory.Keyboard,
    type: SettingType.Shortcut,
    defaultValue: 'Ctrl+C',
    currentValue: 'Ctrl+C',
    tags: ['快捷键', '复制', '编辑', 'shortcut', 'copy'],
    group: 'edit'
  },

  // 文件设置
  {
    id: 'files.defaultEncoding',
    name: '默认编码',
    description: '新建文件的默认字符编码',
    category: SettingsCategory.Files,
    type: SettingType.Select,
    defaultValue: 'utf8',
    currentValue: 'utf8',
    tags: ['编码', '文件', '默认', 'encoding', 'file'],
    group: 'encoding',
    validation: {
      options: [
        { value: 'utf8', label: 'UTF-8' },
        { value: 'gbk', label: 'GBK' },
        { value: 'ascii', label: 'ASCII' }
      ]
    }
  },

  // 高级设置
  {
    id: 'advanced.maxMemoryUsage',
    name: '最大内存使用',
    description: '应用程序可使用的最大内存（MB）',
    category: SettingsCategory.Advanced,
    type: SettingType.Number,
    defaultValue: 1024,
    currentValue: 1024,
    tags: ['内存', '性能', '限制', 'memory', 'performance'],
    group: 'performance',
    validation: {
      min: 256,
      max: 8192
    }
  }
];

export class SettingsSearchService {
  private static settings: BaseSetting[] = SETTINGS_DEFINITIONS;

  // 搜索设置
  static searchSettings(query: string): SettingSearchResult[] {
    if (!query.trim()) {
      return [];
    }

    const normalizedQuery = query.toLowerCase().trim();
    const results: SettingSearchResult[] = [];

    this.settings.forEach(setting => {
      const score = this.calculateRelevanceScore(setting, normalizedQuery);
      if (score > 0) {
        const matchInfo = this.getMatchInfo(setting, normalizedQuery);
        results.push({
          setting,
          matchType: matchInfo.type,
          matchText: matchInfo.text,
          score
        });
      }
    });

    // 按相关性分数排序
    return results.sort((a, b) => b.score - a.score);
  }

  // 计算相关性分数
  private static calculateRelevanceScore(setting: BaseSetting, query: string): number {
    let score = 0;

    // 名称匹配（最高权重）
    if (setting.name.toLowerCase().includes(query)) {
      score += 20;
      // 精确匹配额外加分
      if (setting.name.toLowerCase() === query) {
        score += 30;
      }
      // 开头匹配额外加分
      if (setting.name.toLowerCase().startsWith(query)) {
        score += 10;
      }
    }

    // 描述匹配
    if (setting.description.toLowerCase().includes(query)) {
      score += 10;
    }

    // 标签匹配
    if (setting.tags) {
      setting.tags.forEach(tag => {
        if (tag.toLowerCase().includes(query)) {
          score += 5;
          // 精确匹配标签额外加分
          if (tag.toLowerCase() === query) {
            score += 10;
          }
        }
      });
    }

    // ID匹配（用于高级用户）
    if (setting.id.toLowerCase().includes(query)) {
      score += 8;
    }

    // 分类匹配
    const categoryName = this.getCategoryName(setting.category);
    if (categoryName.toLowerCase().includes(query)) {
      score += 3;
    }

    // 组匹配
    if (setting.group && setting.group.toLowerCase().includes(query)) {
      score += 2;
    }

    return score;
  }

  // 获取匹配信息
  private static getMatchInfo(setting: BaseSetting, query: string): { type: 'name' | 'description' | 'tag', text: string } {
    // 优先级：名称 > 标签 > 描述
    if (setting.name.toLowerCase().includes(query)) {
      return { type: 'name', text: setting.name };
    }

    if (setting.tags) {
      const matchingTag = setting.tags.find(tag => 
        tag.toLowerCase().includes(query)
      );
      if (matchingTag) {
        return { type: 'tag', text: matchingTag };
      }
    }

    if (setting.description.toLowerCase().includes(query)) {
      return { type: 'description', text: setting.description };
    }

    return { type: 'name', text: setting.name };
  }

  // 按分类过滤设置
  static getSettingsByCategory(category: SettingsCategory): BaseSetting[] {
    return this.settings.filter(setting => setting.category === category);
  }

  // 按组过滤设置
  static getSettingsByGroup(category: SettingsCategory, group: string): BaseSetting[] {
    return this.settings.filter(setting => 
      setting.category === category && setting.group === group
    );
  }

  // 获取所有分类
  static getAllCategories(): SettingsCategory[] {
    const categories = new Set(this.settings.map(setting => setting.category));
    return Array.from(categories);
  }

  // 获取分类下的所有组
  static getGroupsByCategory(category: SettingsCategory): string[] {
    const groups = new Set(
      this.settings
        .filter(setting => setting.category === category)
        .map(setting => setting.group)
        .filter(group => group !== undefined)
    );
    return Array.from(groups) as string[];
  }

  // 获取设置定义
  static getSettingDefinition(settingId: string): BaseSetting | undefined {
    return this.settings.find(setting => setting.id === settingId);
  }

  // 获取分类名称
  private static getCategoryName(category: SettingsCategory): string {
    const categoryNames = {
      [SettingsCategory.Editor]: '编辑器',
      [SettingsCategory.Appearance]: '外观',
      [SettingsCategory.Keyboard]: '快捷键',
      [SettingsCategory.Files]: '文件',
      [SettingsCategory.Extensions]: '扩展',
      [SettingsCategory.Advanced]: '高级'
    };
    return categoryNames[category] || category;
  }

  // 获取建议搜索词
  static getSuggestedSearchTerms(): string[] {
    const terms = new Set<string>();
    
    this.settings.forEach(setting => {
      // 添加名称中的关键词
      setting.name.split(/\s+/).forEach(word => {
        if (word.length > 1) {
          terms.add(word.toLowerCase());
        }
      });
      
      // 添加标签
      if (setting.tags) {
        setting.tags.forEach(tag => {
          if (tag.length > 1) {
            terms.add(tag.toLowerCase());
          }
        });
      }
    });

    return Array.from(terms).sort();
  }

  // 高级搜索
  static advancedSearch(options: {
    query?: string;
    category?: SettingsCategory;
    type?: SettingType;
    group?: string;
    modified?: boolean;
  }): SettingSearchResult[] {
    let filteredSettings = [...this.settings];

    // 按分类过滤
    if (options.category) {
      filteredSettings = filteredSettings.filter(s => s.category === options.category);
    }

    // 按类型过滤
    if (options.type) {
      filteredSettings = filteredSettings.filter(s => s.type === options.type);
    }

    // 按组过滤
    if (options.group) {
      filteredSettings = filteredSettings.filter(s => s.group === options.group);
    }

    // 按修改状态过滤
    if (options.modified !== undefined) {
      filteredSettings = filteredSettings.filter(s => {
        const isModified = s.currentValue !== s.defaultValue;
        return options.modified ? isModified : !isModified;
      });
    }

    // 如果有查询词，进行文本搜索
    if (options.query && options.query.trim()) {
      const query = options.query.toLowerCase().trim();
      const results: SettingSearchResult[] = [];

      filteredSettings.forEach(setting => {
        const score = this.calculateRelevanceScore(setting, query);
        if (score > 0) {
          const matchInfo = this.getMatchInfo(setting, query);
          results.push({
            setting,
            matchType: matchInfo.type,
            matchText: matchInfo.text,
            score
          });
        }
      });

      return results.sort((a, b) => b.score - a.score);
    }

    // 没有查询词时，返回所有过滤后的设置
    return filteredSettings.map(setting => ({
      setting,
      matchType: 'name' as const,
      matchText: setting.name,
      score: 1
    }));
  }
}
